<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
    public  function index(){
        return view('user.login');
    }
    public function login(Request $request){
        $this->validate($request,[
            'email'=>'bail|required|email',
            'password'=>'bail|min:6|max:18',
            'is_remember'=>'integer'
        ]);
        $user=$request->all(['email','password']);
        $is_remember=boolval($request->input('is_remember'));
        if(\Auth::attempt($user,$is_remember)){
            $user=User::where('email',$user['email'])->first();
            if($user->status==1){
                return redirect('article')->with('message','登录成功');
            }else{
                $token=md5($user->name.$user->password.time());
                return view('emails.reActive')->with(['email'=>$user->email,'title'=>'激活账户','token'=>$token]);
            }
        }
        return redirect()->back()->withErrors('登录失败');
    }
    public function logout(){
        \Auth::logout();
        return redirect('login');
    }
    public function email(Request $request){
//        dd($request->all());
        $info=$request->all();
        //发送邮件
        $to=$info['email'];//邮件地址
        $subject=$info['title'];//邮件标题
        \Mail::send('emails.active',['token'=>$info['token']],function ($message) use($to,$subject){
            $message->to($to)->subject($subject);
        });
        User::where('id',Auth::id())->update([
            'token'=>$info['token'],
            'token_exptime'=>time()+60*60*24
        ]);
        return redirect('login')->with('message','邮件已发送请激活');
    }
}
